Repository navigation
Infer loop invariants for the int locals a loop changes (Houdini) - #551
Conversation
Codex review, round 1I found no false negative in the programs I ran. The branch reported refinement errors for the tested decrements, resets, continue paths, nested loops, switch paths, and try/finally path. It verified the ordinary counter examples that the pre-PR build rejects.
Code quality: |
Codex round 1: what was doneNo false negative found. The three findings are precision gaps; all declined for this PR and listed in the PR body under "Known precision gaps":
Code quality ( |
Codex review, round 2No false negative found in round 2. I compiled the branch once and ran the adversarial programs under codex544. No repository files were changed.
I found no new code-quality issue material to this review. No false negative in two rounds; the Codex loop for this PR ends here. |
Clean-code reviewAudit of this PR's own new code (
|
800c30e to
3775ff5
Compare
2bd898a to
ddbe7c3
Compare
A loop forgot everything about the int locals it changes but their declared refinements, so for (int i = 0; i < 10; i++) use(i) did not know i >= 0. With the Houdini algorithm, the candidate invariants that the facts before the loop prove are added to the instances at the loop head; each check of the body drops those not proved where the next iteration starts (end of the body, after a for's update, after a do-while's condition, which now holds there), until none is dropped, within the loop that already re-checks the body until its typestates are stable. The candidate proofs are silent. Where continues join at the end of the body, the candidates and whether each variable grew or shrank since the head are kept when proved at every continue and at the end of the body. After 8 checks that dropped candidates, all are dropped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3775ff5 to
cfc266a
Compare
…eak (#552) Stacked on #551; review/merge after it. Fixes #545 Part of the loop invariant inference plan (#542). ## What and why After a loop, the variables it changes were havocked again: only their declared refinements were known, so after `int i = 0; while (i < n) i++;` nothing said `i >= n`. Now, after a loop that can only exit at its head through its condition, the instances after the loop get the invariants inferred in #551 and the negated condition: - `exitsAtHeadThroughCondition`: a `while`, `for` or for-each loop (not a `do`-`while`), with no `break` whose target is the loop (labelled or not), and a condition that writes no variable. - `InvariantCandidates.condition` translates the condition when it is built of `&&`, `||`, `!` and comparisons (`<`, `<=`, `>`, `>=`, `==`, `!=`) of the terms a candidate may mention (int literals, int locals and parameters, `+`, `-`, `*`); otherwise only the invariants are added. - `LoopInvariants.afterLoop` adds them to the post-loop instances (after the existing havoc), like the head facts. Also (found by the Codex review): `TryChecker` starts a catch block from any value a variable had in the try block, including values recorded in loop-body checks that name join instances of a dropped check. The post-loop instance used to be `true`, which hid them; with facts after the loop they surfaced as `Variable #i_11 could not be found` (already the case on main for a refined variable). The variable is now unknown in the catch block when such a value is among them. ## Soundness argument - The invariants hold at the loop head on every visit (#551), including the last one, where the condition is evaluated to false and the loop exits. - For `while`/`for` without `break`, the code after the loop is reached only from that point (a `return`, `throw` or labelled jump to an outer statement does not reach it), and the condition writes nothing, so the state after the loop is the head state where the condition was false: the invariants and the negated condition describe it. - A `do`-`while` exits after its body and condition, where the head invariants need not hold (`do { i = i + 5; } while (i < 3);` keeps `i <= 3` at the head but exits with `i == 5`), so it is excluded. A condition with a side effect (`while (i++ < 10)`) exits in a state after the head, so it is excluded too. - The negated condition is built from the same Java expression with pure terms only, so it means what the condition meant at the exit. - Making a variable unknown in a catch block only removes facts. ## Before / after `int i = 0; while (i < n) i++; atLeast(i, n);` (`@Refinement("_ <= i") int n`): before `Refinement Error` (only `i`'s declared refinement known), after `Correct`. `for (; i < 10; i++) { if (next()) continue; } ten(i);` (`_ == 10`): before `Refinement Error`, after `Correct` (invariant `i <= 10` and `!(i < 10)`). ## Tests - `CorrectLoopExitFacts` (the first two fail on #551 alone): `i >= n` after counting up with `while`; `i == 10` after a `for` whose body has a continue; a loop in a try with a catch (spurious `Not Found Error` without the `TryChecker` change). - `ErrorLoopExitFacts`: no negated condition after a loop with `break`; none after a `do`-`while` (the example above); none after a condition that increments (`while (i++ < 10)` exits with `i == 11`). - `InvariantCandidatesTest.translatesConditionsOverTheSameTerms`: `!`, `||`, `&&`, `==`, `!=` translated; conditions with calls or a literal `true` not. Full suite passes locally. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Stacked on #550; review/merge after it.
Fixes #544
Fixes #537
Fixes #479
Part of the loop invariant inference plan (#542).
What and why
A loop havocs every variable it changes: at the loop head a changed variable keeps only its declared refinement, so
for (int i = 0; i < 10; i++) use(i)did not knowi >= 0(#537). This PR infers invariants for theintlocal variables (and parameters) a loop changes, with the Houdini algorithm (Flanagan and Leino, FME 2001) over the candidates of #550 (Liquid Types qualifiers):new LoopInvariants, before the havoc): keep the candidates that the facts before the loop prove (x0is the instance before the loop).startIteration): add the remaining candidates to the refinements of the loop-head instances (not as a path condition, which an assignment would rename or drop).recordNextIteration): at the point where the next iteration starts (end of the body forwhile/for-each, after the update forfor, after the condition fordo-while, where the condition is now assumed since the next iteration only starts when it holds) drop each candidate not proved for the last instances.scanBodyhavocs the changed variables again. There, the candidates and "xgrew / shrank since the head" are kept when proved at every continue and at the fall-through end of the body (atJoin/joined), so aforupdate or ado-whilecondition that follows can still be checked.checkUntilFixpointloop (which already re-checks the body until typestates are stable and keeps only the errors of the last check). After 8 checks that dropped candidates, all are dropped (MAX_ROUNDS).All candidate proofs are silent (
checkStateSMT(..., silent = true)); a failed or unknown proof only drops the candidate. Loops whose jumps run afinallyor leave a labelled block (followsJumpsfalse) infer nothing, as their typestates are not followed either.Soundness argument
A candidate survives only if (a) it is proved from the facts before the loop, and (b) in the last check, assuming all survivors at the head, it is proved at every point where the next iteration starts: the end of the body (if reachable), the update or condition after it, and every
continue(through the join facts, each proved on every path into the join). So the survivors form an inductive invariant and hold at the head on every iteration; errors are only kept from that last check. An earlier check assumes more candidates (and fewer typestates) than the last one, so an error that stops it is also an error of the last one. Integers are mathematical, as elsewhere in LiquidJava.Checked with Codex (no false negative found) and these programs that must still be rejected: decrementing counter with
_ >= 0, counter reset in the body,i = i - 2on some path, a bound the step breaks (i += 3underi < 10with_ <= 10), a continue path that decreasesi(inwhile, and inforbefore the update), an inner loop that decreases the outer counter, labelled continue from an inner loop, switch and try/finally in the body.Before / after
for (int i = 0; i < 10; i++) use(i)found i < 10 but expected i >= 0while (total < 1024) { use(total); total = total + 1; }found total < 1024 but expected total >= 0read(buf, total, limit - total)withoff >= 0,if (n < 0) break; total += n;)found total < limit but expected total >= 0@Refinement("_ >= 0 && _ <= 1024") total, guard thentotal = total + n)for (int i = 0; i < l.size(); i++) l.get(i)... i < #size_result but expected i >= 0 && i < size(l)#479 needed only
i >= 0: the list is not havocked (itssize()andgetdo not change its state), so the plan's #546 (candidates from what the body requires) is not needed for it.Tests
CorrectLoopInvariants(each method fails without this PR): False error: a counter updated in a loop is only known by the loop condition (for (int i = 0; i < 10; i++) does not prove i >= 0) #537's counter and accumulator, the buffer loop, a symbolic start (for (int i = k; ...)afterif (k < 0) return;), nested loops (jstarts ati), and a continue infor,whileanddo-while.ErrorLoopInvariants(non-inductive candidates must not be assumed): decrementing counter, reset in the body, decreased on some path, bound not kept by the step, decreased before a continue (inwhile, and inforbefore the update), decreased in an inner loop.classes/loop_list_index_correct: the A for loop over indices forgets the list's ghost, so i < l.size() does not prove l.get(i) #479 reproducer.Timing
Full suite, same machine, two runs each (machine shared, so noisy): main 195 s / 170 s wall, TestExamples 127 s / 86 s; this PR 163 s / 142 s wall, TestExamples 98 s / 91 s. On the same pair of runs, the 16 existing loop fixtures take 1.3 to 2 times as long (e.g.
CorrectLoopStateFixpoint2.3 s to 3.6 s,CorrectLoopCondition0.37 s to 0.79 s): each check of a loop body now also runs one silent SMT query per candidate, and a dropped candidate costs one more check of the body. Tuning (caps, nested loops re-inferred per outer check) is #547.Known precision gaps (from the Codex review, left for later)
forupdate ordo-whilecondition that repairs a value set before acontinue(i = -1; continue;theni++) is not followed: the join keeps only facts proved before the update.finallyanywhere on a jump path turns inference off for the whole loop, as for typestates.🤖 Generated with Claude Code